﻿using System;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace MyTools
{
    public class Req
    {
        public string url { get; set; }
        public string param { get; set; }
        public string method { get; set; }
        public string contType { get; set; }
    }

    public class TxtTool
    {
        private static string TXT_PATH = "req.txt";

        /// <summary>
        /// 从文本文件中，加载请求连接和请求参数
        /// </summary>
        /// <returns></returns>
        internal static List<Req> LoadReqFromTxt()
        {
            List<Req> lst = new List<Req>();
            try
            {
                List<string> lines = ReadTxt2Lines();
                foreach (string line in lines)
                {
                    Req req = line2Req(line);
                    if (req != null)
                    {
                        lst.Add(req);
                    }
                }
            }
            catch (Exception e)
            {
                //MessageBox.Show("加载文件出错");
            }
            return lst;
        }

        public static Boolean SaveReq2Text(Req req)
        {
            Boolean flag = false;
            if (!File.Exists(TXT_PATH))
            {
                // 创建、写入
                FileStream fs = new FileStream(TXT_PATH, FileMode.Create, FileAccess.ReadWrite);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine("{0},{1}", req.url, req.param);
                sw.Flush();
                sw.Dispose();
                sw.Close();
                fs.Close();
                flag = true;
            }
            else
            {
                // 创建、写入
                FileStream fs = new FileStream(TXT_PATH, FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine("{0},{1}", req.url, req.param);
                sw.Flush();
                sw.Dispose();
                sw.Close();
                fs.Close();
                flag = true;
            }
            return flag;
        }

        /// <summary>
        /// 读取文本文件中的每一行数据，放到一个list集合中
        /// </summary>
        /// <returns></returns>
        static List<string> ReadTxt2Lines()
        {
            List<string> lines = new List<string>();
            try
            {
                if (File.Exists(TXT_PATH))
                {
                    StreamReader sr = new StreamReader(TXT_PATH);
                    // 读第一行数据
                    string line = sr.ReadLine();
                    while (line != null && line.Length > 0)
                    {
                        lines.Add(line);
                        // 读下一行
                        line = sr.ReadLine();
                    }
                    sr.Close();
                }
            }
            catch (Exception e)
            {
                //MessageBox.Show("读取文件中的数据报错");
            }
            return lines;
        }

        /// <summary>
        /// 删除文本文件中的请求连接和参数
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        internal static bool deleteReqFromTxt(int index)
        {
            Boolean b = false;

            if (File.Exists(TXT_PATH) && index >= 0)
            {
                List<string> lines = ReadTxt2Lines();
                if (lines.Count > 0)
                {
                    File.Delete(TXT_PATH);
                    lines.RemoveAt(index);
                    foreach (string line in lines)
                    {
                        Req req = line2Req(line);
                        if (req != null)
                        {
                            SaveReq2Text(req);
                        }
                    }
                }

            }
            return b;
        }

        /// <summary>
        /// 将文本文件中的请求记录转换为req对象
        /// </summary>
        /// <param name="line"></param>
        /// <returns></returns>
        private static Req line2Req(string line)
        {
            string[] vs = line.Split(',');
            if (vs.Length >= 2)
            {
                Req req = new Req()
                {
                    url = vs[0],
                    param = vs[1],
                    method = "POST",
                    contType = "FORM"
                };
                return req;
            }
            return null;
        }
    }

    public class JsonTool
    {

        public static string FormatJsonStr(string json)
        {
            string retStr = "";
            if (json.Length == 0)
            {
                return retStr;
            }

            try
            {
                JsonSerializer serializer = new JsonSerializer();
                TextReader tr = new StringReader(json);
                JsonTextReader jtr = new JsonTextReader(tr);
                object obj = serializer.Deserialize(jtr);
                if (obj != null)
                {
                    StringWriter textWriter = new StringWriter();
                    JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                    {
                        Formatting = Formatting.Indented,
                        Indentation = 4,//缩进字符数
                        IndentChar = ' '//缩进字符
                    };
                    serializer.Serialize(jsonWriter, obj);
                    retStr = textWriter.ToString();
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("错误的JSON");
            }
            return retStr;
        }
        /// <summary>
        /// 对form参数进行格式化
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        internal static string FormatFormParam(string param)
        {
            string retStr = "";
            if (param.Length == 0)
            {
                return retStr;
            }

            string[] pas = param.Split('&');
            foreach (string pa in pas)
            {
                if (pa.Length > 0)
                {
                    retStr += "&" + pa + "\r\n";
                }
            }
            return retStr;
        }

        /// <summary>
        /// TextBox的内容格式化成form表单参数
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        internal static string Text2FormParam(string text)
        {
            string retStr = "";
            if (text.Length == 0)
            {
                return retStr;
            }

            string[] pas = text.Split('&');
            foreach (string pa in pas)
            {
                if (pa.Length > 0)
                {
                    string temp = pa;
                    // "userName=ex_dengcc2\r\n"
                    if (pa.EndsWith("\r\n"))
                    {
                        temp = pa.Substring(0, pa.Length - 2);
                    }
                    retStr += "&" + temp;
                }
            }
            return retStr;
        }
    }
}
